package com.slw.caiji.controller;

import com.slw.caiji.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.util.UUID;

@RestController
@Api(tags = "上传文件接口")
public class UploadFileController {

    @Value("${upload.file-path}")
    private String path;

    @Value("${upload.chatroom-path}")
    private String chatRoomPath;

    @PostMapping("/api/upload/file")
    @Operation(summary = "上传文件", description = "上传文件到服务器")
    public Result uploadFile(MultipartFile file) throws IOException {
        String filename = file.getResource().getFilename();
        if (filename == null) {
            return Result.fail(504, "文件名称为空");
        }
        String extName = filename.substring(filename.lastIndexOf("."));
        String fileName = LocalDate.now().toString().replace("-", "") + "-" + UUID.randomUUID().toString().replace("-", "") + extName;
        File newFile = new File(path + fileName);
        file.transferTo(newFile);
        return Result.success(fileName);
    }


    @PostMapping("/api/upload/chatroom-file")
    @Operation(summary = "上传文件", description = "上传文件到服务器")
    public Result uploadChatRoomFile(MultipartFile file) throws IOException {
        String filename = file.getResource().getFilename();
        if (filename == null) {
            return Result.fail(504, "文件名称为空");
        }
        String extName = filename.substring(filename.lastIndexOf("."));
        String fileName = LocalDate.now().toString().replace("-", "") + "-" + UUID.randomUUID().toString().replace("-", "") + extName;
        File newFile = new File(chatRoomPath + fileName);
        file.transferTo(newFile);
        return Result.success(fileName);
    }

}
